import { createMemoryHistory, createRouter } from "vue-router";

import MainView from "../views/Main.vue";
import LoginView from "../views/Login.vue";

const routes = [
  {
    path: "/",
    component: MainView,
    redirect: "/checkout",
    children: [
      {
        path: "/checkout",
        name: "Checkout",
        component: () => import("../views/checkout/Index.vue"),
      },
      {
        path: "/order",
        name: "Order",
        component: () => import("../views/order/Index.vue"),
      },
      {
        path: "/goods",
        name: "Goods",
        component: () => import("../views/goods/Index.vue"),
      },
      {
        path: "/stock",
        name: "Stock",
        component: () => import("../views/stock/Index.vue"),
      },
      {
        path: "/chart",
        name: "Chart",
        component: () => import("../views/chart/Index.vue"),
      },
      {
        path: "/setting",
        name: "Setting",
        component: () => import("../views/setting/Index.vue"),
      },
      {
        path: "/purchase",
        name: "Purchase",
        component: () => import("../views/purchase/Index.vue"),
      },
      {
        path: "/service",
        name: "Service",
        component: () => import("../views/service/Index.vue"),
      },
    ],
  },
  { path: "/login", component: LoginView },
];

const router = createRouter({
  history: createMemoryHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  if (!localStorage.getItem("access_token")) {
    if (to.path == "/login") {
      next();
    } else {
      next("/login");
    }
  } else {
    next();
  }
});

export default router;
